package io.gitee.chearnee.fw.openapi.filter;

import io.gitee.chearnee.fw.openapi.processor.PreProcessor;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 2021/9/17 20:02
 */
@Order(-1)
@Component
@AllArgsConstructor
@Slf4j
public class OpenApiFilter extends OncePerRequestFilter {

  private final PreProcessor preProcessor;

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                  FilterChain filterChain) throws ServletException, IOException {
    OpenApiHttpServletRequestWrapped requestWrapped = null;
    if (!(request instanceof OpenApiHttpServletRequestWrapped)) {
      requestWrapped = new OpenApiHttpServletRequestWrapped(request);
    } else {
      requestWrapped = (OpenApiHttpServletRequestWrapped) request;
    }
    if (!request.getRequestURI().contains("checkDeath")) {
      log.info("请求数据:header:{},body:{}", getRequestHeader(requestWrapped),
          requestWrapped.getRequestParams());
    }
    preProcessor.initContext(requestWrapped);
    filterChain.doFilter(requestWrapped, response);
    preProcessor.disposeContext();
  }

  public Map<String, String> getRequestHeader(HttpServletRequest request) {
    Map<String, String> ret = new HashMap<>();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      ret.put(headerName, request.getHeader(headerName));
    }
    return ret;
  }
}
